import React, {useEffect, useState} from 'react';
import {Upload, message, Row, Col, Space, Button, Typography, Input, DatePicker, Form, Tabs} from 'antd';
import {InboxOutlined, PlayCircleOutlined, FileExcelOutlined} from "@ant-design/icons";
import FileListTable from "./FileListTable";
import { request, base_url } from "../utils/requset";
import dayjs from 'dayjs'; // 导入 dayjs 用于日期处理

const {Dragger} = Upload;
const {Title} = Typography;

function FileUpload() {
    const [form] = Form.useForm();
    const [importList, setImportList] = useState([]);
    const [runLoading, setRunLoading] = useState(false);
    const [refreshFlag, setRefreshFlag] = useState(() => {
        // 从 localStorage 中读取上次选择的 tab 状态，如果没有则默认为 '1'
        return localStorage.getItem('selectedTab') || '1';
    });

    useEffect(() => {
        try {
            request.get('/rpa/pdfDownload/config').then(response => {
                const data = response.data;
                form.setFieldsValue({
                    pzrq: [dayjs(data.start_date), dayjs(data.end_date)],
                    start_pz_no: data.start_pz_no,
                    end_pz_no: data.end_pz_no,
                });
            });
        } catch (error) {
            if (error.response) {
                message.error(`获取配置失败: ${error.response.data.message}`);
            } else {
                console.error('获取配置失败:', error);
                message.error('获取配置失败，请稍后再试。');
            };
        }
    }, []);

    const fileDownload = async (name) => {
        try {
            const response = await request.get('/rpa/mode/fileDownload?name=' + name, {
                responseType: 'blob' // 告诉 request 返回的是二进制文件
            });
        
            // 创建一个URL对象，指向Blob
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', name); // 这里的name是文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
          console.error('Error downloading file:', error);
        }
      };

    const props = {
        name: 'file',
        multiple: true,
        directory: false,  // 禁止选择文件夹
        accept: '.xlsx,.xlsm',
        action: base_url+'/rpa/file_upload/upload',
        onChange(info) {
            const {status, response} = info.file;
            console.log(info.file)
            if (status === 'done') {
                message.success(`文件 ${info.file.name} 上传成功`);
                setImportList([...importList, response.fileId])
            } else if (status === 'removed') {
                setImportList(importList.filter(file => file !== response.fileId));
            } else if (status === 'error') {
                if (response && response.error) {
                    message.error(`文件 ${info.file.name} 上传失败，参考错误信息：${response.error}`);
                } else if (response) {
                    message.error(`文件 ${info.file.name} 上传失败，参考错误信息：${JSON.stringify(response)}`);

                }
            }
        },
        onDrop(e){
            // 获取拖拽的文件或文件夹
            const items = e.dataTransfer.items;
            for (let i = 0; i < items.length; i++) {
              const item = items[i];

              // 如果是文件夹，阻止上传
              if (item.kind === 'folder' || item.type === ""||
                  item.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  && item.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.macroEnabled.12"
                  && item.type !== "application/vnd.ms-excel.sheet.macroEnabled.12"
              ) {
                message.error('不支持的文件格式或文件夹');
                e.preventDefault();  // 阻止文件夹的拖拽行为
                return;
              }
            }
        },
    };

    // 新增函数：打印文件列表
    const printFileList = async () => {
        if (refreshFlag === '1') {
            if (importList.length === 0) {
                message.warning('请先上传文件');
                return;
            };
            try {
                const payload = {
                    type: 'excel',
                    list: importList,
                };
                setRunLoading(true);
                await request.post('/rpa/pdfDownload/run', payload);
                message.success('保存成功！');
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } catch (error) {
            if (error.response) {
                message.error(`保存失败: ${error.response.data.message}`);
            } else {
                console.error('保存配置失败:', error);
                message.error('保存配置失败，请稍后再试。');
            }
            } finally {
            setRunLoading(false);
            }
        } else {
            try {
                const data = form.getFieldsValue();
                const payload = {
                    type: 'config',
                    data: {
                        start_date: dayjs(data.pzrq[0]).format('YYYY-MM-DD'), 
                        end_date: dayjs(data.pzrq[1]).format('YYYY-MM-DD'),
                        start_pz_no: data.start_pz_no,
                        end_pz_no: data.end_pz_no,
                    },
                };
                setRunLoading(true);
                await request.post('/rpa/pdfDownload/run', payload);
                message.success('保存成功！');
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } catch (error) {
            if (error.response) {
                message.error(`保存失败: ${error.response.data.message}`);
            } else {
                console.error('保存配置失败:', error);
                message.error('保存配置失败，请稍后再试。');
            }
            } finally {
            setRunLoading(false);
            }
        };
        
    };

    useEffect(() => {
        // 监听 refreshFlag 的变化，当变化时保存到 localStorage
        localStorage.setItem('selectedTab', refreshFlag);
    }, [refreshFlag]);

    const tabItems = [
        {
            key: '1',
            label: '按Excel下载',
            children: 
            <Dragger {...props} style={{marginBottom: '16px', height: '150px'}}>
                <p className="ant-upload-drag-icon">
                    <InboxOutlined/>
                </p>
                <p className="ant-upload-text">点击或拖拽文件到此区域以上传文件</p>
                <p className="ant-upload-hint">
                    支持上传Excel文件.xlsx和.xlsm格式; 支持多文件上传
                </p>
            </Dragger>
        },
        {
            key: '2',
            label: '按日期下载',
            children: 
            <Form form={form} >
                <Row justify="center">
                    <Col xs={24} sm={20} md={24}>
                        {/* 日期选择 */}
                        <Col xs={24} sm={12} md={12}>
                        <Form.Item
                            label="凭证日期"
                            name="pzrq"
                            style={{marginBottom: 27.49}}
                            rules={[{ required: true, message: '请选择日期!' }]}>
                            <DatePicker.RangePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
                        </Form.Item>
                        </Col>
                        <Col xs={24} sm={12} md={12}>
                        <Form.Item
                            label="起始凭证号"
                            name="start_pz_no"
                            style={{marginBottom: 27.49}}
                        >
                            <Input style={{ width: '100%' }} />
                        </Form.Item>
                        </Col>
                        <Col xs={24} sm={12} md={12}>
                        <Form.Item
                            label="终止凭证号"
                            name="end_pz_no"
                            style={{marginBottom: 27.49}}
                        >
                            <Input style={{ width: '100%' }} />
                        </Form.Item>
                        </Col>
                    </Col>
                </Row>
            </Form>
        }
    ];

    return (
        <Row justify="center">
            <Col xs={24} sm={20} md={24}>
                <Title level={3} style={{ height: '32px', marginBottom: '16px' }}>
                    联合打印
                    <Space style={{ float: 'right' }}>
                        <Button onClick={() => fileDownload('模板（公开）.xlsx')} hidden={refreshFlag!=='1'}>
                            <FileExcelOutlined />下载Excel模板
                        </Button>
                        <Button type="primary" onClick={printFileList} loading={runLoading}>
                            <PlayCircleOutlined />运行
                        </Button>
                    </Space>
                </Title>
                <div style={{ minHeight: 'calc(100vh - 128px)' }} >
                    <Tabs 
                        items={tabItems} 
                        activeKey={refreshFlag} 
                        onChange={(key) => setRefreshFlag(key)}
                    >
                    </Tabs>
                    <FileListTable />
                </div>
            </Col>
        </Row>
    );
}

export default FileUpload;